package com.store.app.utils;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.Signature;
import android.hardware.Camera;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListAdapter;
import android.widget.ListView;

import com.store.app.LocationApplication;
import com.store.app.utils.http.MD5;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

import org.apache.http.NameValuePair;
import org.json.JSONObject;

import java.io.ByteArrayInputStream;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Utils {

    public final static String CoorType_GCJ02 = "gcj02";
    public final static String CoorType_BD09LL = "bd09ll";
    public final static String CoorType_BD09MC = "bd09";
    /***
     * 61 ： GPS定位结果，GPS定位成功。
     * 62 ： 无法获取有效定位依据，定位失败，请检查运营商网络或者wifi网络是否正常开启，尝试重新请求定位。
     * 63 ： 网络异常，没有成功向服务器发起请求，请确认当前测试手机网络是否通畅，尝试重新请求定位。
     * 65 ： 定位缓存的结果。
     * 66 ： 离线定位结果。通过requestOfflineLocaiton调用时对应的返回结果。
     * 67 ： 离线定位失败。通过requestOfflineLocaiton调用时对应的返回结果。
     * 68 ： 网络连接失败时，查找本地离线定位时对应的返回结果。
     * 161： 网络定位结果，网络定位定位成功。
     * 162： 请求串密文解析失败。
     * 167： 服务端定位失败，请您检查是否禁用获取位置信息权限，尝试重新请求定位。
     * 502： key参数错误，请按照说明文档重新申请KEY。
     * 505： key不存在或者非法，请按照说明文档重新申请KEY。
     * 601： key服务被开发者自己禁用，请按照说明文档重新申请KEY。
     * 602： key mcode不匹配，您的ak配置过程中安全码设置有问题，请确保：sha1正确，“;”分号是英文状态；且包名是您当前运行应用的包名，请按照说明文档重新申请KEY。
     * 501～700：key验证失败，请按照说明文档重新申请KEY。
     */

    public static float[] EARTH_WEIGHT = {0.1f, 0.2f, 0.4f, 0.6f, 0.8f}; // 推算计算权重_地球
    //public static float[] MOON_WEIGHT = {0.0167f,0.033f,0.067f,0.1f,0.133f};
    //public static float[] MARS_WEIGHT = {0.034f,0.068f,0.152f,0.228f,0.304f};

    public static String getCurrentTime() {
        Date date = new Date();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
        String str = format.format(date);
        return str;
    }

    /**
     * 日期+四位随机数
     * @return
     */
    public static String getTheDateAndRandom(){
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Random random = new Random();
        try {
            Date   curDate   =   new   Date(System.currentTimeMillis());//获取当前时间
            String   s_curDate   =   simpleDateFormat.format(curDate);
            s_curDate=s_curDate.replace("-", "");

            int s = random.nextInt(9999-1000+1)+1000;
            return s_curDate+s;
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return "0000";
    }
    public static String getTime(Calendar mCalendar) {
        Date date = new Date(mCalendar.getTimeInMillis());
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
        String str = format.format(date);
        return str;
    }
    public static String getTime1(Calendar mCalendar) {
        Date date = new Date(mCalendar.getTimeInMillis());
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
        String str = format.format(date);
        return str;
    }
    public static String genPackageSign(List<NameValuePair> params, String security_code) {
        StringBuilder sb = new StringBuilder();

        for (int i = 0; i < params.size(); i++) {
            sb.append(params.get(i).getName());
            sb.append('=');
            sb.append(params.get(i).getValue());
            sb.append('&');
        }
        sb.deleteCharAt(sb.length() - 1);
        sb.append(security_code);

        Log.i("signStr", sb.toString());

        String packageSign = MD5.getMessageDigest(sb.toString().getBytes());
        return packageSign;
    }

    public static String genMd5(String seed) {
        String packageSign = MD5.getMessageDigest(seed.getBytes());
        return packageSign;
    }

    public static boolean isNumber(String str){
        String rule = "[0-9]*";
        return validate(rule,str);
    }

    public static String getPhotoFileName() {
        Date date = new Date(System.currentTimeMillis());
        SimpleDateFormat dateFormat = new SimpleDateFormat(
                "'IMG'_yyyyMMdd_HHmmss", Locale.getDefault());
        return dateFormat.format(date) + ".jpg";
    }
    //将json格式的字符串转换为map
    public static Map<String, String> getMapForJson(String jsonStr){
        JSONObject jsonObject ;
        try {
            jsonObject = new JSONObject(jsonStr);

            Iterator<String> keyIter= jsonObject.keys();
            String key;
            String value ;
            Map<String, String> valueMap = new HashMap<String, String>();
            while (keyIter.hasNext()) {
                key = keyIter.next();
                value = jsonObject.getString(key);
                valueMap.put(key, value);
            }
            return valueMap;
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 将map转换为json格式
     * @param map
     * @return
     */
    public static String mapToJson(Map<String ,String > map){
        if(map==null||map.isEmpty()){
            return "null";
        }
        JSONObject jsonObj = new JSONObject();
        try{
            for(String key : map.keySet()){
                String value = map.get(key);
                jsonObj.put(key,value);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return jsonObj.toString();
    }
    public static void getSingInfo(Context context) {
        try {
            PackageInfo packageInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), PackageManager.GET_SIGNATURES);
            Signature[] signs = packageInfo.signatures;
            Signature sign = signs[0];
            parseSignature(sign.toByteArray());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static void  Setlistview(ListView listview){
        ListAdapter la=listview.getAdapter();
        int totalHeight=0;

        int len=listview.getCount();
        for(int i=0;i<len;i++){
            View listItem=la.getView(i, null, listview);
            listItem.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
            totalHeight+=listItem.getMeasuredHeight();
        }

        ViewGroup. LayoutParams params=listview.getLayoutParams();
        params.height=totalHeight+(listview.getDividerHeight()*(la.getCount()-1));
        listview.setLayoutParams(params);
    }
    public static void parseSignature(byte[] signature) {
        try {
            CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
            X509Certificate cert = (X509Certificate) certFactory.generateCertificate(new ByteArrayInputStream(signature));
            String pubKey = cert.getPublicKey().toString();
            String signNumber = cert.getSerialNumber().toString();
            System.out.println("signName:" + cert.getSigAlgName());
            System.out.println("pubKey:" + pubKey);
            System.out.println("signNumber:" + signNumber);
            System.out.println("subjectDN:" + cert.getSubjectDN().toString());
        } catch (CertificateException e) {
            e.printStackTrace();
        }
    }

    public static String getVersion() {
        try {
            PackageManager manager = LocationApplication.app.getPackageManager();
            PackageInfo info = manager.getPackageInfo(LocationApplication.app.getPackageName(), 0);
            String version = info.versionName;
            return version;
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }
    //判断是否是手机号
    public static boolean matchPhone(String text) {
        String rule = "^1([38][0-9]|4[579]|5[0-3,5-9]|6[6]|7[0135678]|9[89])\\d{8}$";
        return validate(rule,text);
    }
    /**
     * 对字段串进行正则规则校验
     * @param rule
     * @param str
     * @return
     */
    public static boolean validate(String rule,String str){
        boolean isExist = false;
        Pattern pattern = Pattern.compile(rule);
        Matcher matcher = pattern.matcher(str);
        boolean b = matcher.matches();
        if (b) {
            isExist = true;
        }
        return isExist;
    }
    /**
     * 是否安装了微信
     * @param context
     * @return
     */
    public static boolean isWXAppInstalledAndSupported(Context context) {
        IWXAPI msgApi = WXAPIFactory.createWXAPI(context, null);
        msgApi.registerApp(SettingData.APP_ID);

        boolean sIsWXAppInstalledAndSupported = msgApi.isWXAppInstalled()
                && msgApi.isWXAppSupportAPI();

        return sIsWXAppInstalledAndSupported;
    }


    private static long lastClickTime;
    public synchronized static boolean isFastClick() {

        long time = System.currentTimeMillis();
        Log.v("zyl","time:"+time);
        Log.v("zyl","lastClickTime:"+lastClickTime);
        Log.v("zyl","result:"+(time - lastClickTime));

        if ( time - lastClickTime < 2000) {
            return true;

        }
        lastClickTime = time;
        return false;
    }

    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }
    public static boolean isCameraPermission() {
        try {
            Camera.open().release();
            return true;
        } catch (Exception e) {
            return false;
        }

    }

    public static String getMonthStartData(){
        SimpleDateFormat dateFormater = new SimpleDateFormat(
                "yyyy-MM-dd");
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.DAY_OF_MONTH, 1);
        cal.getTime();
        return dateFormater.format(cal.getTime()) + "";
    }
    public static String getMonthEndData(){
        SimpleDateFormat dateFormater = new SimpleDateFormat(
                "yyyy-MM-dd");
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.DAY_OF_MONTH,
                cal.getActualMaximum(Calendar.DAY_OF_MONTH));
        return dateFormater.format(cal.getTime()) + "";
    }

}
